//
//  SeaView.m
//  BattleshipRevolution
//
//  Created by YellowPepper VietNam on 11/27/12.
//  Copyright (c) 2012 YPVN. All rights reserved.
//

#import "SeaView.h"

@implementation SeaView
@synthesize maxTargets, targets;
@synthesize map;

- (void) dealloc
{
    [targets release];
    [super dealloc];
}

- (id) init
{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}

- (void) initialize
{
    maxTargets = 10;
    targets = [[NSMutableArray alloc] init];
    
    map = [[Map alloc] init];
}

- (void) drawRect:(CGRect)rect
{
    //draw something
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextClearRect(c, rect);
    
    [[UIImage imageNamed:@"sea_blue.png"] drawInRect:CGRectMake(0, 0, 320, 320)];
    CGContextSaveGState(c);
    for (int i = 0; i < map.cells.count; i++) {
        CellMap *cell = [map.cells objectAtIndex:i];
        if ([cell isFired]) {
            CGContextSetFillColorWithColor(c, [[UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:0.5] CGColor]);
            CGContextAddRect(c, CGRectMake(cell.cellPosition.x*cell.cellSize.width, cell.cellPosition.y*cell.cellSize.height, cell.cellSize.width, cell.cellSize.height));
        }
    }
    CGContextFillPath(c);
    
    
    CGContextRestoreGState(c);
    UIImage *image = [UIImage imageNamed:@"target.png"];
    for (NSNumber *number in [targets objectEnumerator]) {
        int offset = [number integerValue];
        int x = offset / (int)map.cellSize.width;
        int y = offset % (int)map.cellSize.height;
        
        [image drawInRect:CGRectMake(x*map.cellSize.width + (map.cellSize.width - 40) / 2, y*map.cellSize.height + (map.cellSize.height - 40)/2, 40, 40)];
    }
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint point = [touch locationInView:self];
            
    int x = point.x / map.cellSize.width;
    int y = point.y / map.cellSize.height;
    
    int index = x + y*map.mapSize.width;
    
    for (NSNumber *number in [targets objectEnumerator]) {
        int target = [number integerValue];
        if (index == target) {
            [targets removeObject:number];
            [self setNeedsDisplay];
            return;
        }
    }
    
    if (targets.count == maxTargets) {
        return;
    }
    
    [targets addObject:[NSNumber numberWithInt:index]];
    [self setNeedsDisplay];

}

@end
